package pl.textureStudio.data
{
	import pl.error.InternalError;
	import pl.textureStudio.data.vo.StudioTextureVO;

	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	/**
	 * @author michalr
	 */
	public class DataService implements IDataService
	{
		private static var secure:Boolean;
		private var storage:IStorage;
		private var completeHandler:Function;
		private var loader:URLLoader;

		public function DataService( storage:IStorage )
		{
			if (secure == false) throw new Error( InternalError.CREATION_ERROR );
			this.storage = storage;
			loader = new URLLoader();
			loader.addEventListener( Event.COMPLETE, onLoadComplete );
		}

		public static function factory( storage:IStorage ):IDataService
		{
			secure = true;
			var o:IDataService = new DataService( storage );
			return o;
		}

		public function loadData( path:String, completeHandler:Function ):void
		{
			this.completeHandler = completeHandler;
			loader.load( new URLRequest( path ) );
		}

		private function onLoadComplete( event:Event ):void
		{
			var xml:XML = XML( loader.data );
			var node:XML;
			var arr:Array = [];
			for each (node in xml..textureData)
			{
				arr.push( StudioTextureVO.factory( node ) );
			}
			storage.setData( arr );
			if (completeHandler != null) completeHandler();
		}

		public function saveData( data:Array ):void
		{
		}
		
		
	}
}
